import React, {
  useState, useCallback, useEffect,
} from 'react'
import {
  Text, View, SafeAreaView, Image,
} from 'react-native'
import { RouterKey } from '@NAVIGATION/NavigationType'
import Navigation from '@NAVIGATION/Navigation'
import EStyleSheet from 'react-native-extended-stylesheet'
import BottomToTop from '@COMPONENTS/BottomToTop'
import Images from '@IMAGE'
import BleManager from '@UTILS/BleManager'
import Permissions from '@UTILS/Permissions'
import { State } from 'react-native-ble-plx'
import BluetoothStateManager from 'react-native-bluetooth-state-manager'
import { BleConnectivityStatus } from '@CONSTANTS/BleConstants'
import { isIOS } from '@UTILS/Common'
import LinearGradientButton from '@COMPONENTS/button/LinearGradient'
import CustomerService from '@COMPONENTS/modal/CustomerService'
import Toast from '@COMPONENTS/Toast'
import AnalyticsUtil, { ANALYTICS_EVENT } from '@UTILS/AnalyticsUtil'

const data = [
  {
    title: '你好～ \n请连接纳瑞维',
    desc: '',
    btnText: '开始连接',
    eventTitle: '引导连接页-1】首次进入App，引导连接设备',
  },
  {
    title: '打开手机蓝牙，并开启纳瑞维设备',
    desc: '缓慢闪烁的绿色灯，表示设备已开启',
    btnText: '绿灯已闪烁',
    eventTitle: '【引导连接页-2】引导打开手机蓝牙/开启设备',
  },
  {
    title: '设备连接中…',
    desc: '将纳瑞维设备，靠近您的智能手机',
    disabled: true,
    btnText: '',
    eventTitle: '【引导连接页-3】连接中',
  },
  {
    title: '连接成功，来学学如何使用纳瑞维吧',
    desc: '',
    btnText: '马上学习',
    eventTitle: '引导连接页-4】连接成功',
  },
]
const errorData = {
  [State.PoweredOff]: {
    title: '请打开手机蓝牙',
    desc: '要将您的设备连接到手机应用程序，需要打开手机蓝牙',
    btnText: '打开蓝牙',
    eventTitle: '【异常报错页-蓝牙未打开】',
    src: Images.bluetoothGuide.notTurnOn,
    list: [],
  },
  [BleConnectivityStatus.SearchingTimedOut]: {
    title: '未发现纳瑞维设备',
    desc: '',
    btnText: '重新连接',
    eventTitle: '【异常报错页-设备未找到】',
    src: Images.bluetoothGuide.notTurnOn,
    list: [
      '确保纳瑞维设备是打开状态',
      '请打开手机蓝牙',
      '将纳瑞维放置在手机附近',
    ],
  },
  [BleConnectivityStatus.AuthenticationFailed]: {
    title: '身份验证失败',
    desc: '该设备已关联其他账号，请连接一个新设备',
    btnText: '连接新设备',
    eventTitle: '【异常报错页-设备已关联其他账号】',
    src: Images.bluetoothGuide.noPermission,
    list: [],
  },
}
const errorKey = Object.keys(errorData)

const BluetoothGuide: React.FC = () => {
  const [idx, setIndex] = useState(0)
  const [bleState, setBleState] = useState<State|BleConnectivityStatus>(State.PoweredOff)
  const {
    title, desc, disabled = false, btnText, eventTitle,
  } = data[idx]

  const isError = [State.PoweredOff, BleConnectivityStatus.SearchingTimedOut, BleConnectivityStatus.AuthenticationFailed].includes(bleState)
  // @ts-ignore
  const errorDetail = isError ? errorData[bleState] : errorData[State.PoweredOff]
  const showError = idx > 1 && errorKey.includes(bleState) && bleState !== BleConnectivityStatus.Searching
  console.log(idx, bleState, isError)
  const skipToHome = useCallback(() => {
    Navigation.replace(RouterKey.Root)
    AnalyticsUtil.onEvent(ANALYTICS_EVENT.tap_splash_guide_skip.eventId, { Title: eventTitle })
  }, [eventTitle])
  // @ts-ignore
  const guid = Images.bluetoothGuide[`guide${idx}`]

  const onNext = () => {
    if (idx < data.length - 1) {
      if (idx > 1 && (!isError)) {
        return
      }
      if (bleState === BleConnectivityStatus.SearchingTimedOut) {
        // 触发重新连接
        setBleState(State.PoweredOn)
        return
      }
      if (bleState === BleConnectivityStatus.AuthenticationFailed) {
        // 连接新设备
        BleManager.connect(null, (error1, info1) => {
          console.log('connect-listener', error1, info1)
        })
        return
      }
      setIndex(idx + 1)
    }
    if (idx === data.length - 1) {
      Navigation.replace(RouterKey.DeviceGuide, {
        fromPage: RouterKey.BluetoothGuide,
      })
    }
  }

  const customerService = () => { CustomerService.show() }

  const onNextApi = useCallback(async () => {
    switch (bleState) {
      case (State.PoweredOff): {
        if (isIOS) {
          BluetoothStateManager.openSettings()
        } else {
          const p = await Permissions.allPrerequisitesOK()
          if (p) {
            BluetoothStateManager.enable()
          } else {
            const granted = await Permissions.requestBluPermission()
            if (!granted) {
              Toast.info('需要开启权限使用')
            } else {
              BluetoothStateManager.enable()
            }
          }
        }
        break
      }

      case State.PoweredOn: {
        // android 需要额外权限
        const p = await Permissions.allPrerequisitesOK()

        if (!isIOS && !p) {
          const granted = await Permissions.requestBluPermission()
          if (!granted) {
            Toast.info('需要开启权限使用')
            setBleState(State.Unauthorized)
            return
          }
          BleManager.connect(null, (error1, info1) => {
            console.log('connect-listener', error1, info1)
          })
        } else {
          BleManager.connect(null, (error1, info1) => {
            console.log('connect-listener', error1, info1)
          })
        }

        break
      }
      case State.Unauthorized: {
        break
      }
      default: {
        break
      }
    }
  }, [bleState])

  useEffect(() => {
    if (idx > 1) {
      onNextApi()
    }
  }, [bleState, idx, onNextApi])

  useEffect(() => {
    BleManager.init()
    console.log('isEnabledBlu', Permissions.isEnabledBlu())
    const sub = BleManager.onStateChange(async (newState) => {
      console.log('onStateChange', newState)
      const p = await Permissions.isEnabledBlu()
      if (isIOS && !p) {
        console.log('State.Unauthorized')
        return
      }
      setBleState(newState)
    }, true)
    BleManager.addPeripheralConnectionStateListener((status) => {
      console.log('BleConnectivityStatus', status)
      if (status === BleConnectivityStatus.Searching) {
        setIndex(2)
      }
      if ([BleConnectivityStatus.SearchingTimedOut, BleConnectivityStatus.Disconnected].includes(status)) {
        setBleState(BleConnectivityStatus.SearchingTimedOut)
      }
      if (status === BleConnectivityStatus.AuthenticationFailed) {
        setBleState(BleConnectivityStatus.AuthenticationFailed)
      }
      if (status === BleConnectivityStatus.Connected) {
        setBleState(status)
        setIndex(3)
      }
    })
    return () => {
      BleManager.remove(sub)
      BleManager.stopDeviceScan()
      BleManager.removeAllPeripheralConnectionStateListener()
    }
  }, [])

  return (
    <SafeAreaView style={styles.container}>
      <Text
        style={[styles.skip, disabled && styles.disabled]}
        onPress={skipToHome}
      >
        跳过
      </Text>
      <Text style={styles.title}>{title}</Text>
      <Text style={styles.desc}>{desc}</Text>
      <View style={styles.imageContainer}>
        <Image source={guid} />
      </View>

      <LinearGradientButton
        style={[styles.button, styles.next, disabled && styles.hidden]}
        onPress={onNext}
      >
        <Text style={[styles.buttonText]}>{btnText}</Text>
      </LinearGradientButton>

      {showError ? (
        <BottomToTop toValue={44}>
          <View style={styles.container}>
            <Text style={[styles.title, styles.errorTitle]}>
              {errorDetail?.title}
            </Text>

            <Text style={[styles.desc, styles.errorDesc]}>
              {errorDetail.desc}
            </Text>

            <View style={styles.imageContainer}>
              {bleState !== 'SearchingTimedOut' && <Image source={errorDetail.src} />}
              {errorDetail.list.map((v, i) => (
                <View key={v} style={styles.noDeviceItem}>
                  <Image source={Images.bluetoothGuide[`noDevice${i + 1}`]} />
                  <Text style={styles.noDeviceText}>{v}</Text>
                </View>
              ))}
            </View>

            <Text style={styles.customer} onPress={customerService}>
              联系客服帮助
            </Text>

            <LinearGradientButton
              style={[styles.button, styles.next]}
              onPress={onNext}
            >
              <Text style={[styles.buttonText]}>{errorDetail.btnText}</Text>
            </LinearGradientButton>
          </View>
        </BottomToTop>
      ) : null}
    </SafeAreaView>
  )
}

export default BluetoothGuide

const styles = EStyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '$bgColor',
  },
  skip: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '#595959',
    textAlign: 'right',
    paddingRight: 16,
    paddingTop: 8,
    paddingBottom: 14,
    height: 44,
  },
  hidden: {
    opacity: 0,
  },
  disabled: {
    color: '#C2C2C2',
  },
  title: {
    fontSize: 24,
    fontFamily: 'AlibabaPuHuiTiB',
    color: '$fontColor',
    lineHeight: 33,
    paddingTop: 36,
    marginLeft: 28,
    maxWidth: 267,
  },
  desc: {
    paddingTop: 12,
    paddingLeft: 28,
    fontSize: 16,
    fontFamily: 'PingFangSC-Light',
    fontWeight: '300',
    color: '#595959',
    lineHeight: 22,
  },
  imageContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
  },
  button: {
    alignSelf: 'center',
    width: 206,
    height: 49,
    borderRadius: 25,
    marginBottom: 48,
  },
  buttonText: {
    fontSize: 18,
    fontFamily: 'PingFangSC-Medium',
    fontWeight: '500',
    color: '$white',
    lineHeight: 25,
  },
  next: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorTitle: {
    marginLeft: 0,
    maxWidth: '100%',
    textAlign: 'center',
  },
  errorDesc: {
    paddingLeft: 28,
    paddingRight: 28,
    textAlign: 'center',
  },
  customer: {
    fontSize: 14,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '#8C8C8C',
    lineHeight: 20,
    marginBottom: 16,
    textAlign: 'center',
  },
  noDeviceItem: {
    flexDirection: 'row',
    paddingLeft: 50,
    paddingRight: 58,
    alignItems: 'center',
    justifyContent: 'flex-start',
    marginBottom: 12,
  },
  noDeviceText: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '#595959',
    lineHeight: 24,
    marginLeft: 16,
    width: 145,
  },
})
